import { createRouter, createWebHistory } from 'vue-router'
// import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home', // 重定向到 /home
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/page/HomePage.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/page/LoginPage.vue'),
    }, 
    {
      path: '/aboutUs',
      name: 'aboutUs',
      component: () => import('../views/page/AboutUsPage.vue'),
    }, 
    {
      path: '/myAccount',
      name: 'user-info',
      component: () => import('../views/page/UserInfoPage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/addWeb',
      name: 'addWeb',
      component: () => import('../views/AddWebPage.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/try',
      name: 'try',
      component: () => import('../views/component/try.vue')
    },
    {
      path: '/cs',
      name: 'cs',
      component: () => import('../views/InitialView.vue')
    },
    {
      path: '/Vla',
      name: 'vla',
      component: () => import('../views/InitialView.vue')
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

router.beforeEach((to, from, next) => {
  const isLogged = localStorage.getItem('isLoggedIn') === 'true'; // 假设登录状态存储在 localStorage
  const requiresAuth = to.meta?.requiresAuth; // 检查目标路由是否需要认证

  if (requiresAuth && !isLogged) {
    next({ path: '/login' });
    return;
  }

  // 如果用户已登录，检查权限
  if (isLogged) {
    if (to.path === '/sample') {
      const userPower = Number(window.sessionStorage.getItem('dataset')); // 转换为数字
      if (userPower === 1) {
        return next();
      } else {
        ElMessage.error('您没有此权限');
        return next(false); // 阻止导航
      }
    } 
  }

  // 其他情况正常放行
  next();
});

export default router
